package com.ps.aop;

import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.ps.actions.BaseAction;
import com.ps.actions.person.LoginAction;
import com.ps.entity.Result;
import com.ps.global.Globals;
import com.ps.pojo.person.Employee;
import com.ps.service.person.EmployeeService;
import com.ps.service.setting.RoleService;
import com.ps.util.Kit;

/**
 * 权限判断
 * @author Administrator
 *
 */
public class AuthorityInterceptor implements  Interceptor{
	
	@Autowired
    private RoleService roleService;
	
	
	public String intercept(ActionInvocation arg0) throws Exception {
		System.out.println("AuthorityInterceptor start");
        
		Object actionobj = arg0.getAction();
		Map<String, String> params = arg0.getProxy().getConfig().getParams();
		
		if (!(actionobj instanceof BaseAction)) {
			return null;
		} 
		if (actionobj instanceof LoginAction) {
			return arg0.invoke();
		}
		Integer permissionId  = Kit.INTEGER_VALIDATOR.validate(params.get(Globals.PERMISSION_FLAG));
		if (permissionId == null) return null;
		
		BaseAction action = (BaseAction)actionobj;
		Map<String, Object> session = action.getSession();
		Employee user =  (Employee)session.get(Globals.SESSION_USER);
		
		
		
		if (user == null) {
			return 	BaseAction.LOGIN;
		} else {
			Integer roleId = user.getRoleId(); 
			
			if (roleId == Globals.ADMIN_ROLE_ID) {
				return arg0.invoke();
			}
			
			Set<Integer> permissions = roleService.queryPermissionIdsByRoleId(roleId);
			if (permissions == null) return null; 
			
			if (permissions.contains(permissionId)) {
				return arg0.invoke();
			} else {
/*				System.out.println("AuthorityInterceptor fail");
				ServletActionContext.getResponse().setContentType("text/html");
				ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
				ServletActionContext.getResponse().getWriter().print("<script type='text/javascript' >alert('沒有权限!');history.back();</script>");*/
				System.out.println("AuthorityInterceptor 没有权限");
				return BaseAction.ERR_AUTHORITY;
			}
		}
		
	}

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void init() {
		// TODO Auto-generated method stub
		
	}

}
